part of common_lib_plugin;

/// ClassName [FileUtil]
///
/// Description:
/// Author: 乔
/// Date: 2023/5/26

class FileUtil {
  static int fileLength(File file) {
    RandomAccessFile? sFile;
    int fileLength = 0;
    try {
      sFile = file.openSync();
      fileLength = sFile.lengthSync();
    } finally {
      sFile?.close();
    }
    return fileLength;
  }

  static String fileSizeShow(File? file) {
    if (file == null) return '';
    return fileSizeShowByLength(file.lengthSync());
  }

  static String fileName(String? path) {
    if (path == null) return '';
    var name = path.substring(path.lastIndexOf('/') + 1);
    if (name.contains('?path=') && name.contains('&token=')) {
      name = name.substring(name.indexOf('?path=') + 6, name.indexOf('&token='));
    } else if (name.contains('?')) {
      name = name.substring(0, name.indexOf('?'));
    }
    return name;
  }

  static String fileExtension(String? path) {
    if (path == null) return '';
    return path.substring(path.lastIndexOf('.') + 1);
  }

  static String fileSizeShowByLength(int length) {
    var convertedSize = length.toDouble();
    var tokens = ["B", "KB", "MB", "GB", "TB"];
    var factor = 0;
    while (convertedSize >= 1024) {
      if (factor > 4) {
        break;
      }
      convertedSize = convertedSize / 1024;
      factor = factor + 1;
    }
    if (factor == 0) {
      return '${convertedSize.toInt()}${tokens[factor]}';
    } else {
      return '${convertedSize.truncateAsString()}${tokens[factor]}';
    }
  }
}
